package com.junjie.blibli.aspect;

import com.junjie.blibli.Constant.AuthRoleConstant;
import com.junjie.blibli.Entity.UserMoment;
import com.junjie.blibli.Entity.auth.UserRole;
import com.junjie.blibli.Exception.http.ConditionException;
import com.junjie.blibli.Support.UserSupport;
import com.junjie.blibli.service.UserRoleService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Aspect
@Component
public class DataLimitedAspect {
    @Autowired
    private UserSupport userSupport;

    @Autowired
    private UserRoleService userRoleService;

    //切点
    @Pointcut("@annotation(com.junjie.blibli.annotation.DataLimited)")
    public void check(){};

    @Before("check()")
    public void doBefore(JoinPoint joinPoint){
        Long userId = userSupport.getCurrentUserId();
        //获取该用户的角色
        List<UserRole> userRoleList = userRoleService.getUserRoleByUserId(userId);
        Set<String> roleCodeSet = userRoleList.stream().map(UserRole::getRoleCode).collect(Collectors.toSet());
        //获取原方法形参上的参数
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if(arg instanceof UserMoment){
                UserMoment userMoment = (UserMoment) arg;
                String type = userMoment.getType();
                //这里是示范例子，就是等级为LV1的只能发布type为0的动态
                if(roleCodeSet.contains(AuthRoleConstant.ROLE_LV0) && !"0".equals(type)){
                    throw new ConditionException("参数异常");
                }
            }
        }

    }

}
